#include <time.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/file.h>


#define LOG_FILE "myinetd.log"

void log_message(char *filename, char *message)
{
  time_t mytime;
  FILE *logfile;
  char buf[50];

  if(filename)
    logfile=fopen(filename,"a");
  else
    logfile = stdout;
  if(!logfile) return;
  flock(fileno(logfile), LOCK_EX);


  mytime = time(NULL);
  sprintf(buf, "%s", ctime(&mytime));
  strtok(buf, "\n");
  fprintf(logfile,"%s>> %s\n", buf, message);


  flock(fileno(logfile), LOCK_UN);
  if(filename)
    fclose(logfile);
}


int main(int argc, char **argv) {
  time_t t;
  struct sockaddr_in their_addr;   
  int sin_size = sizeof(struct sockaddr_in);
  char c;
  int n;
  char message[100];

  getpeername(0, (struct sockaddr *)&their_addr, &sin_size);
  sprintf(message, "Daytime: Sending current date to %s:%u",inet_ntoa(their_addr.sin_addr), ntohs(their_addr.sin_port));
  log_message(LOG_FILE, message);

  do {
    ioctl(0, FIONREAD, &n);
    if(n>0) {
      read(0, &c, 1);
    }
  } while(n>0);
  
  time (&t);
  printf ("%s", ctime(&t));

  fflush(stdout);

  return 0;
}
